<?php
    include 'dbconf.php';
    include 'dbopen.php';
    include 'functions.php';

	/*
	 * Get file locations from Misc/localization_files.txt
	 */

	$locFile = file("../Misc/localization_files.txt");
	foreach ($locFile as $locFileLine) {
    	if(substr($locFileLine,0,12) == "Rscript_path"){
    		$Rscript_path = trim(str_replace("=","",str_replace("Rscript_path","",$locFileLine))); 
    	}
	}

	if(file_exists("../Images/genes_vs_clinical.png")){
    	unlink("../Images/genes_vs_clinical.png");
	}
	if(file_exists("../TXT/raw_data.xls")){
    	unlink("../TXT/raw_data.xls");
	}

    /*
     * Receive variables from $_POST
     */

	$input_clinical_var = "";
    foreach($_GET['PickList'] as $k=>$v){
       //echo $k;
       //echo "$v<br />";
       $input_clinical_var = "$v"."\r".$input_clinical_var;
    }
	
    
    $input_gene_sym = $_GET['input_gene_sym'];
    $input_gene_sym = preg_split('/\r/', $input_gene_sym);

    $input_clinical_var = preg_split('/\r/', $input_clinical_var);
    //pop removes the last element in array, in this case we remove the empty array created because the split was on \n
    array_pop($input_clinical_var); //pop removes the last element in array, in this case we remove the empty array created because the split was on \n

    // Remove any empty rows or trailing newlines
    $input_gene_sym = removeEmptyRows($input_gene_sym);
    // Check for bogus gene symbols
    checkGeneSyms($input_gene_sym);
    
    $input_tissue = $_GET['bike_tissue'];

    /*
     * find size of input genes
     */

    $nbrOfInputGenes = sizeof($input_gene_sym);
	
	
    /*
     * Start loop over input genes
     */

    /*
     * Initiating global variable $d;
     * Used to name pictures and pdf
     */
    global $d;
    $d=0;

    /*
     * Initiating global variable $c, that will be used as counter variable
     * in the loop through all genes.
     */
    global $c;
    $c=0;
    
	$arrayOfExpValues = array();
	$arrayOfClinValues = array();
	$annotationArray = array();

    while ($c < $nbrOfInputGenes) {


        foreach ($input_clinical_var as $individual_clinical_var) {
            /*
             * trim removes trailing characters such as whitespace.
             * This is just a safety precaution.
             */
            $individual_clinical_var = trim($individual_clinical_var);
            $trimmed_genesym = trim($input_gene_sym[$c]);
            /*
             * Find probe_id with mysql_query.
             * The probe_id is used in the next mysql_query which is needed for a join.
             */
            $probe_id_res = mysql_query(getProbeIdFromGeneSymbol($trimmed_genesym));

            /*
             * find number of rows in probe_id that needs to be looped over.
             */
            $nrows_probe_id = mysql_numrows($probe_id_res);

            /*
             * Initiating global counting variable $l, that will be used as a
             * counting variable for the loop over all probe_ids.
             */
            global $l;
            $l=0;




            /*
             * Loop over the rows of probe_ids with the use of counter $l
             */
            while ($l < $nrows_probe_id) {

                $individual_probe_id = mysql_result($probe_id_res,$l,'probe_id');

                /*
                 * Trim procedure
                 */
                $individual_probe_id = trim($individual_probe_id);
                /*
                 * The mysql_query that joins clinical ind_nbr with expression
                 * ind_nbr. In theori its the intersect between the two datasets
                 * with one probe_id and one clinical variable
                 */
               
                $joinQueryResult = mysql_query(getCLINvarProExpl($individual_clinical_var, $individual_probe_id, $input_tissue))
                        or die ("ERROR: could not send/execute query: getCLINvarProExpl ".  mysql_error());;

                $nbrRowsJoinQuery=mysql_numrows($joinQueryResult);

                /*
                 * Initiating global variables that will be used temporary
                 */
                global $ind_nbr; $ind_nbr = "";
                global $ind_nbr_temp; $ind_nbr_temp = "";
                global $clinical_var; $clinical_var = "";
                global $exp_level; $exp_level = "";
                global $el_temp; $el_temp = "";
                global $clinical_temp; $clinical_temp = "";

                $k=0;
                while ($k < $nbrRowsJoinQuery) {
                    $clinical_temp = mysql_result($joinQueryResult,$k); //first field is clinical_var
                    $el_temp = mysql_result($joinQueryResult,$k,'exp_level');
                    $ind_nbr_temp = mysql_result($joinQueryResult,$k,'ind_nbr');


         
                    $clinical_var = $clinical_var . "\t" . $clinical_temp;
                    $exp_level = $exp_level . "\t" . $el_temp;
                    $ind_nbr = $ind_nbr . "\t" . $ind_nbr_temp;

                    $k++;
                }
                    

                /*
                 * Not sure if removing the tab space in the beginning of
                 * the string is necessary
                 *
                 * The tab in the beginning of $snp and $probe_id is necessary to
                 * get the correct format
                 */

                $exp_level = preg_replace('/\t/', '', $exp_level,1);
                //$clinical_var = preg_replace('/\t/', '', $clinic_var,1);


                $clinical_var_array = preg_split('/\t/', $clinical_var, -1, PREG_SPLIT_NO_EMPTY);
                $exp_level_array = preg_split('/\t/', $exp_level, -1, PREG_SPLIT_NO_EMPTY);
                $ind_nbr_array = preg_split('/\t/', $ind_nbr, -1, PREG_SPLIT_NO_EMPTY);
				
				
				$arrayOfClinValues[$individual_clinical_var] = $clinical_var_array;
				
				

#                $clinical_varFile = "../TXT/clinical_var.txt";
#                $fh_clinical_varFile = fopen($clinical_varFile, 'w');
#                fwrite($fh_clinical_varFile, "\t".$individual_clinical_var."\r");
#
#                $nbrOfIndividuals = count($ind_nbr_array);
#                for ($counter=0; $counter < $nbrOfIndividuals; $counter++) {
#                    fwrite($fh_clinical_varFile, $ind_nbr_array[$counter]."\t");
#                    fwrite($fh_clinical_varFile, $clinical_var_array[$counter]."\r");
#                }
#                fclose($fh_clinical_varFile);
#
#

				$arrayOfExpValues[$individual_probe_id] = $exp_level_array;

#                $explvlFile = "../TXT/explvl.txt";
#                $fh_explvlFile = fopen($explvlFile, 'w');
#                fwrite($fh_explvlFile, "\t".$individual_probe_id."\r");
#
#                $nbrOfIndividuals = count($ind_nbr_array);
#                for ($counter=0; $counter < $nbrOfIndividuals; $counter++) {
#                    fwrite($fh_explvlFile, $ind_nbr_array[$counter]."\t");
#                    fwrite($fh_explvlFile, $exp_level_array[$counter]."\r");
#                }
#                fclose($fh_explvlFile);
#
#                /*
#                 * Start of Tissue file creation, thats going to be sent to R.
#                 */
#
#                $tissue_file = "../TXT/tissuetype.txt";
#                $fh_tissuefile = fopen($tissue_file, 'w');
#                fwrite($fh_tissuefile, $input_tissue."\r");
#                fclose($fh_tissuefile);

                /*
                 * Start of annotation file creation, thats going to be sent to R.
                 */

                $AnnotationQueryResult = mysql_query(getAnnotation($individual_probe_id))
                        or die ("ERROR: could not send/execute query getAnnotation!".  mysql_error());

                $temp1 = mysql_fetch_array($AnnotationQueryResult);
                $temp1['gene_sym'];



                $nbrRowsAnnotationQuery=mysql_numrows($AnnotationQueryResult);


                $probe_id_temp = "";
                $gene_sym_temp = "";
                $gene_name_temp = "";

                $k=0;
                while ($k < $nbrRowsAnnotationQuery) {
                    $probe_id_temp = mysql_result($AnnotationQueryResult,$k,'probe_id');
                    $gene_sym_temp = mysql_result($AnnotationQueryResult,$k,'gene_sym');
                    $gene_name_temp = mysql_result($AnnotationQueryResult,$k,'gene_name');

                    $k++;
                }


				$annotationArray[$probe_id_temp] = $gene_sym_temp."\t".$gene_name_temp;
				
				
#                $annotation_file = "../TXT/annotation.txt";
#                $fh_annotationfile = fopen($annotation_file, 'w');
#                fwrite($fh_annotationfile, "\tgenesymbol\tgenename\r");
#                fwrite($fh_annotationfile, $probe_id_temp . "\t" . $gene_sym_temp ."\t" . $gene_name_temp);
#                fclose($fh_annotationfile);
#
#
#                $gene_sym = $trimmed_genesym;
#
#                system("\"C:\Program Files\R\R-2.13.0\bin\Rscript.exe\" ../R/genes_vs_clinical.R $d");
#
#                $nocache = rand();
#                echo "<tr><td><form method=\"post\" action=\"\"><input type=\"checkbox\" name=\"pic_id\" value=\"$d\"></td>
#                          <td><img src='../Images/genes_vs_clinical$d.png?$nocache'></td>
#                      </tr>";


                $d++;
            $l++;
            }

        }
    $c++;
    }
    
    
    
    /*
     * Start of Tissue file creation, thats going to be sent to R.
     */

    $tissue_file = "../TXT/tissuetype.txt";
    $fh_tissuefile = fopen($tissue_file, 'w');
    fwrite($fh_tissuefile, $input_tissue."\r");
    fclose($fh_tissuefile);
    
    
    
    
    
     /*
     * expression file
     */

    $explvlFile = "../TXT/explvl.txt";
    $fh_explvlFile = fopen($explvlFile, 'w');
    
    $probesetsToPrint = array_keys($arrayOfExpValues);
    foreach ($probesetsToPrint as $probeset) {
    	fwrite($fh_explvlFile, "\t"."X".$probeset);
    }
    fwrite($fh_explvlFile, "\r");


    $nbrOfIndividuals = count($ind_nbr_array);
    for ($counter=0; $counter < $nbrOfIndividuals; $counter++) {
        fwrite($fh_explvlFile, $ind_nbr_array[$counter]);
        foreach ($probesetsToPrint as $probeset) {
        	fwrite($fh_explvlFile, "\t".$arrayOfExpValues[$probeset][$counter]);
        	
        }
        fwrite($fh_explvlFile, "\r");
    }
    fclose($fh_explvlFile);
    
    
    
    
        
     /*
     * clinical file
     */

    $clinical_varFile = "../TXT/clinical_var.txt";
    $fh_clinical_varFile = fopen($clinical_varFile, 'w');
    
    $clinVarsToPrint = array_keys($arrayOfClinValues);
    foreach ($clinVarsToPrint as $clinVar) {
    	fwrite($fh_clinical_varFile, "\t"."X".$clinVar);
    }
    fwrite($fh_clinical_varFile, "\r");


    $nbrOfIndividuals = count($ind_nbr_array);
    for ($counter=0; $counter < $nbrOfIndividuals; $counter++) {
        fwrite($fh_clinical_varFile, $ind_nbr_array[$counter]);
        foreach ($clinVarsToPrint as $clinVar) {
        	fwrite($fh_clinical_varFile, "\t".$arrayOfClinValues[$clinVar][$counter]);
        	
        }
        fwrite($fh_clinical_varFile, "\r");
    }
    fclose($fh_clinical_varFile);
    
    
    
    
    
    
    
     /*
     * annotation file
     */

	$annotation_file = "../TXT/annotation.txt";
    $fh_annotationfile = fopen($annotation_file, 'w');
    fwrite($fh_annotationfile, "\tgenesymbol\tgenename\r");

    $probesetsToPrint = array_keys($annotationArray);
    foreach ($probesetsToPrint as $probeset) {
    	fwrite($fh_annotationfile, $probeset."\t".$annotationArray[$probeset]."\r");
    }
    
    
    system("$Rscript_path ../R/genes_vs_clinical.R");

    $nocache = rand();
    echo "
    <td>
    
    <img src='../Images/genes_vs_clinical.png?$nocache'>
    
    </td>";
                    
                    		
					
    
   echo "</table>
   <br>
   
   <a href='../PDF/genes_vs_clinical.pdf?$nocache'>
   PDF-file with plots
   </a>
   <br>
   
   <a href='../TXT/raw_data.xls?$nocache'>
   Text file with raw data
   </a>";


    include 'dbclose.php';
?>